<?php
/**
 * AJAX CRUD Controller Class
 * The following variables are available in this template:
 * - $this: the CrudCode object
 *
 * @author LongLT
 */

class MemberController extends ControllerBase
{
	public function init() {
		Util::app()->theme = ADMIN_THEME;
		parent::init();
		$this->registerFancybox();
	}

	public function registerFancybox(){
		Util::registerScriptFile(Util::themeUrl().'/js/jquery-ui-1.10.3.custom.min.js');
		Util::registerScriptFile(Util::themeUrl().'/js/custome.datepicker.js');
		// Add mousewheel plugin (this is optional)
		Util::registerScriptFile(Util::themeUrl() . '/js/fancybox/jquery.mousewheel-3.0.6.pack.js', CClientScript::POS_HEAD);

		// Add fancyBox main JS and CSS files
		Util::registerScriptFile(Util::themeUrl() . '/js/fancybox/jquery.fancybox.js?v=2.0.6');
		Util::registerCssFile(Util::themeUrl().'/js/fancybox/jquery.fancybox.css?v=2.0.6','screen');

		if (isset($_GET['ajax']))
			$this->layout = '//layouts/none';
	}

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return CMap::mergeArray(parent::filters(),array(
			'accessControl', // perform access control for CRUD operations
		));
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'users'=>Util::getSuperMods(),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Manages all models.
	 */
	public function actionIndex()
	{
		$model=new Member('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Member']))
			$model->attributes=$_GET['Member'];
		else {
			$model->courses_id = date('Y');
		}
		$this->render('index',array(
			'model'=>$model,
		));
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$member 				= $this->loadModel($id);
		$account				= $member->account;
		$announcements			= Announcement::model()->getAsignByMember($id, 'asigned');
		$statistic['asigned']	= AnnouncementAssign::model()->countAsignByMember($id);
		$statistic['joined']	= AnnouncementAssign::model()->countAsignByMember($id, 'joined');
		$statistic['absence']	= $statistic['asigned'] - $statistic['joined'];
		list($codeActive,$codeTrash, $edutionActive, $edutionTrash) = Util::getEducationInfo($member->membercode);
		$courseActive		= $codeActive->courses;
		$logEducationColor	= array('#8ec657', '#777777', '#999999');
		$this->render('view', compact('statistic', 'announcements', 'courseActive', 'member', 'account', 'codeActive', 'codeTrash', 'edutionActive', 'edutionTrash', 'logEducationColor'));
	}

	/**
	 * Creates a new model.
	 */
	public function actionCreate($type = 'basic')
	{
		$member		= new Member;
		$account	= new Account;
		$education	= new Education;
		$membercode	= new MemberCode;
		$semesters 	= $subjects = array();

		// Set active when create
		$account->status 	= STATUS_ACTIVE;
		// Set courses current year
		$membercode->courses_id = date('Y');
		// Set status member type
		$membercode->status	= null;

		if(isset($_POST['Member']))
		{
			// Get data post
			$member->attributes		= $_POST['Member'];
			$membercode->attributes	= $_POST['MemberCode'];

			// Form have education is advance
			if (isset($_POST['Education'])) {
				$type					= 'advance';
				$education->attributes	= $_POST['Education'];
			}
			// Form not have education is basic
			else {
				$type					= 'basic';
			}

			if (isset($_POST['Semester'])) {
				$semesters 				= $_POST['Semester'];
				$subjects 				= $_POST['Subject'];
			}

			// Switch to advance form
			if (isset($_POST['Advance'])) {
				$type = 'advance';
				$member->setScenario($type);
			}
			// Switch to basic form
			else if(isset($_POST['Basic'])){
				$type = 'basic';
				$member->setScenario($type);
			}
			else {
				$member->setScenario($type);
				$education->code_id		= 0;
				$member->user_id		= 0;
				$membercode->user_id	= 0;
				$membercode->code		= 0;
				// Connvert string to lowercase
				$member->fullname		= Util::formatFullName($member->fullname, true);
				// Clear all character non numberic
				$inputPhone				= $member->phone;
				$inputCellPhone			= $member->cellphone;
				$member->phone			= Util::formatPhone($inputPhone, false);
				$member->cellphone		= Util::formatPhone($inputCellPhone, false);

				$validMember 		= $member->validate();
				$validEducation 	= $education->validate();
				$validMemberCode	= $membercode->validate();

				if($validMember && $validEducation && $validMemberCode) {
					$code 			= Util::generalMemberCode($membercode->status, $membercode->courses_id);
					if (mb_strlen($code) == 6) {
						// Create account
						$account->username 			= $code;
						$account->recover_password 	= Util::generalPass();
						$account->password 			= Util::encrypting($account->recover_password);
						$account->email				= $member->email;

						if($account->save()) {
							$userId	= $account->id;
							// Create profile
							$member->user_id	= $userId;
							if (isset($_FILES['Member']['size']['avatar']) && $_FILES['Member']['size']['avatar'] > 0) {
								$avatar 			= CUploadedFile::getInstance($member, 'avatar');
								$tmpNm				= time()-1;
			                	$imageName 			= strtolower($tmpNm . "." . $avatar->getExtensionName());
			                	$member->avatar		= $imageName;
			                	$avatar->saveAs(Util::pathUpload('profile') .'/' . $imageName);
							}

							if ($member->save()) {
								//Create code
								$membercode->user_id 	= $userId;
								$membercode->code 		= $code;
								if ($membercode->save()) {
									//Create education
									$education->code_id = $code;
									if ($education->save()) {
										// Update semester and subject
										if (isset($semesters)) {
											foreach ($semesters as $index => $semester) {
												if (isset($semester['id'])) {
													$semesterModel	= Semester::model()->findByPk($semester['id']);
												}
												else {
													$semesterModel	= new Semester();
												}

												$semesterModel->attributes 		= $semester;
												$semesterModel->education_id	= $education->id;
												$semesterModel->save();

												// Update subject
												foreach ($subjects[$index] as $subject) {
													if (isset($subject['id'])) {
														$subjectModel	= Subject::model()->findByPk($subject['id']);
													}
													else {
														$subjectModel	= new Subject();
													}

													$subjectModel->attributes 		= $subject;
													$subjectModel->semester_id		= $semesterModel->id;
													$subjectModel->save();
												}
											}
										}

										$arrUrl = array('view','id'=>$member->user_id);
										if (isset($_GET['ajax'])) {
											$arrUrl['ajax'] = true;
										}
										$this->redirect($arrUrl);
									}
								}
							}
						}
					}
				}
				$member->fullname 	= Util::formatFullName($member->fullname);
				$member->phone		= $inputPhone;
				$member->cellphone	= $inputCellPhone;
			}
		}
		$paramSemesterForm = array('semesters' => $semesters, 'subjects' => $subjects);
		$this->render('create', compact('type', 'member', 'account', 'education', 'membercode', 'paramSemesterForm'));
	}

	/**
	 * Updates a particular model.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$member		= $this->loadModel($id);
		$account	= $member->account;
		$membercode	= MemberCode::model()->getCode($account->id);
		$education	= Education::model()->getEducation($membercode->code);
		list($semesters, $subjects) = Util::getSemesterInfo($education);
		$semester_delete = $subject_delete = null;

		// Get old avatar
		$oldAvatar	= $member->avatar;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($member);
		if(isset($_POST['Member']))
		{
			// Get data post
			$member->attributes		= $_POST['Member'];
			$education->attributes	= $_POST['Education'];
			$membercode->attributes	= $_POST['MemberCode'];
			if (isset($_POST['Semester'])) {
				$semesters 				= $_POST['Semester'];
				$subjects 				= $_POST['Subject'];
				$subject_delete			= $_POST['subject_id_delete'];
				$semester_delete		= $_POST['semester_id_delete'];
			}


			// Connvert string to lowercase
			$member->fullname		= Util::formatFullName($member->fullname, true);
			// Clear all character non numberic
			$inputPhone				= $member->phone;
			$inputCellPhone			= $member->cellphone;
			$member->phone			= Util::formatPhone($inputPhone, false);
			$member->cellphone		= Util::formatPhone($inputCellPhone, false);

			$validMember 		= $member->validate();
			$validEducation 	= $education->validate();
			$validMemberCode	= $membercode->validate();

			if($validMember && $validEducation && $validMemberCode) {
				// Update account
				$account->email	= $member->email;
				$account->save();

				// Update profile
				if (isset($_FILES['Member']['size']['avatar']) && $_FILES['Member']['size']['avatar'] > 0) {
					$avatar 			= CUploadedFile::getInstance($member, 'avatar');
					$tmpNm				= time()-1;
                	$imageName 			= strtolower($tmpNm . "." . $avatar->getExtensionName());
                	$member->avatar		= $imageName;
                	$avatar->saveAs(Util::pathUpload('profile') .'/' . $imageName);

					if (($oldAvatar != '') && file_exists(Util::pathUpload('profile') .'/' . $oldAvatar)) {
                		unlink(Util::pathUpload('profile') .'/' . $oldAvatar);
                	}
				}
				else {
					$member->avatar 	= $oldAvatar;
				}
				$member->save();

				//Create education
				$education->save();

				// Update semester and subject
				if (isset($semesters)) {
					foreach ($semesters as $index => $semester) {
						if (isset($semester['id'])) {
							$semesterModel	= Semester::model()->findByPk($semester['id']);
						}
						else {
							$semesterModel	= new Semester();
						}

						$semesterModel->attributes 		= $semester;
						$semesterModel->education_id	= $education->id;
						$semesterModel->save();

						// Update subject
						foreach ($subjects[$index] as $subject) {
							if (isset($subject['id'])) {
								$subjectModel	= Subject::model()->findByPk($subject['id']);
							}
							else {
								$subjectModel	= new Subject();
							}

							$subjectModel->attributes 		= $subject;
							$subjectModel->semester_id		= $semesterModel->id;
							$subjectModel->save();
						}
					}
				}

				// Delete subject
				if ($subject_delete != '') {
					$listSubjectDelete = explode(',' , $subject_delete);
					Subject::model()->deleteByPk($listSubjectDelete);
				}

				// Delete semester
				if ($semester_delete != '') {
					$listSemesterDelete = explode(',' , $semester_delete);
					Semester::model()->deleteByPk($listSemesterDelete);
				}


				// Redirect to view
				$arrUrl = array('view','id'=>$member->user_id);
				if (isset($_GET['ajax'])) {
					$arrUrl['ajax'] = true;
				}
				$this->redirect($arrUrl);

			}
			$member->fullname 	= Util::formatFullName($member->fullname);
			$member->phone		= $inputPhone;
			$member->cellphone	= $inputCellPhone;
		}

		$paramSemesterForm = array('semesters' => $semesters, 'subjects' => $subjects, 'subject_delete' => $subject_delete, 'semester_delete' => $semester_delete);
		$this->render('update', compact('member', 'account', 'education', 'membercode', 'paramSemesterForm'));
	}

	/**
	 * Deletes a particular model.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete()
	{
		if(Yii::app()->request->isPostRequest)
		{
			$ids = $_POST['chk'];
			if (is_array($ids))
				foreach ($ids as $key) {
					Member::model()->deleteByPk($key);
					Account::model()->deleteByPk($key);
				}


			$this->setFlash("Dữ liệu đã được xóa.");
			if (isset($_GET['ajax'])) {
				$this->printFlash();
				exit;
			} else {
				$this->redirect(array('index'));
			}
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * actionStatistic
	 */
	public function actionStatistic()
	{
		if(Yii::app()->request->isPostRequest)
		{
			$id		= $_POST['id'];
			$start	= $_POST['start'];
			$end	= $_POST['end'];

			$statistic['announcement'] = array();
			$announcements	= Announcement::model()->getAsignByMember($id, 'asigned', $start, $end);
			if (isset($announcements)) {
				foreach ($announcements as $announcement) {
					$statistic['announcement'][] = $announcement->title;
				}
			}
			$statistic['asigned']		= AnnouncementAssign::model()->countAsignByMember($id, 'asigned', $start, $end);
			$statistic['joined']		= AnnouncementAssign::model()->countAsignByMember($id, 'joined', $start, $end);
			$statistic['absence']		= $statistic['asigned'] - $statistic['joined'];
			echo json_encode($statistic);
			exit;
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');

	}

	/**
	 * actionDownloadExcel()
	 */
	public function actionDownloadExcel() {

		// Get variables
		$id		= isset($_POST['user_id']) ? $_POST['user_id'] : "";
		$start	= isset($_POST["Statistic"]['start_year']) ? $_POST["Statistic"]['start_year'] : "";
		$end	= isset($_POST["Statistic"]['end_year']) ? $_POST["Statistic"]['end_year'] : "";

		if ($id != "") {
			// Get data
			$member 					= $this->loadModel($id);
			$dataPrint["member"]		= $member;
			//$dataPrint["account"]		= $member->account;
			$dataPrint["announcements"] = Announcement::model()->getAsignByMember($id, 'asigned', $start, $end);
			$dataPrint['asigned']		= AnnouncementAssign::model()->countAsignByMember($id, 'asigned', $start, $end);
			$dataPrint['joined']		= AnnouncementAssign::model()->countAsignByMember($id, 'joined', $start, $end);
			$dataPrint['absence']		= $dataPrint['asigned'] - $dataPrint['joined'];
			list($codeActive,$codeTrash, $edutionActive, $edutionTrash) = Util::getEducationInfo($member->membercode);
			$dataPrint["courseActive"]	= $codeActive->courses;
/*			$dataPrint["member_view"]	= array();
			foreach ($dataPrint["announcements"] as $eachMemberView) {
				$member_view = $eachMemberView->member_view->user_id . "#" . $eachMemberView->member_view->announcement_id;
				if (!in_array($member_view, $dataPrint["member_view"]) && $member_view != "#") {
					$dataPrint["member_view"][] = $member_view;
				}
			}*/

			$dataPrint["start"] = $start;
			$dataPrint["end"] = $end;
			// Print excel
			$countData = count($dataPrint["announcements"]);
			$objDownloadExcel = new DownloadExcel();
			$objDownloadExcel->CreateByListControl('member', $dataPrint, $countData);
		}
    }

    public function actionImportMember() {
    	$form		= new MemberImportForm();
    	$listError	= array();

    	if (isset($_POST['MemberImportForm'])) {
    		$check		= false;
    		$validate	= false;
    		if (isset($_FILES['MemberImportForm']['size']['excelMember']) && $_FILES['MemberImportForm']['size']['excelMember'] > 0) {
				$form->excelName	= $_POST['MemberImportForm']['excelName'];
				$form->excelMember	= $_FILES['MemberImportForm']['name']['excelMember'];
				if($form->validate()) {
					$validate			= true;
					$dataMember 		= CUploadedFile::getInstance($form, 'excelMember');
    				$tmpNm				= time()-1;

    				// Check if exist
    				if($form->excelName == '') {
    					$form->excelName	= strtolower($tmpNm . "." . $dataMember->getExtensionName());
    				}
    				else {
    					self::unLinkExcel($form->excelName);
    				}

    				// Upload file
    				$dataMember->saveAs(Util::pathUpload('temp') .'/' . $form->excelName);

    				// Get data form upload
    				$check	= self::saveDataImportMember($form->excelName);
    				if ($check === false) {
    					$form->addError("excelMember", 'Không tìm thấy dữ liệu thành viên trong file vừa chọn.');
    					self::unLinkExcel($form->excelName);
    				}
    				elseif (is_string($check)) {
    					$form->addError("excelMember", $check);
    					self::unLinkExcel($form->excelName);
    				}
    				elseif ($check) {
    					Yii::app()->user->setFlash('recoveryMessage',UserModule::t("Lưu thông tin user thành công."));
			    		$this->refresh();
    				}
	    		}
    		}
    		else {
    			$form->addError("excelMember", 'Bạn chưa chọn file excel chứa dữ liệu thành viên.');
    		}
    	}

    	$this->render('import_member', compact('form'));
    }

    protected function unLinkExcel($excelName) {
    	if (file_exists(Util::pathUpload('temp') .'/' . $excelName)) {
    		unlink(Util::pathUpload('temp') .'/' . $excelName);
    	}
    }

    protected function saveDataImportMember($fileName = '') {
    	$listError		= array();
    	$err_msg 		= "";
		$objImportExcel = new ImportExcel();
		$dataMember		= $objImportExcel->getDataMember($fileName);
		if (!empty($dataMember)) {
			foreach ($dataMember as $row => $data) {
				$member		= new Member;
				$account	= new Account;
				$education	= new Education;
				$membercode	= new MemberCode;
				$semesters 	= $subjects = array();

				// Set active when create
				$account->status 		= STATUS_ACTIVE;
				// Get data post
				$member->attributes		= $data;
				$member->user_id		= 0;
				// Connvert string to lowercase
				$member->fullname		= Util::formatFullName($member->fullname, true);
				// Set courses current year
				$membercode->courses_id = $data['courses_id'];
				// Set status member type
				$membercode->status		= 1;
				$membercode->user_id	= 0;
				$membercode->code		= 0;
				//$education->code_id		= 0;

				// Check validate
				$validMember 		= $member->validate();
				//$validEducation 	= $education->validate();
				$validMemberCode	= $membercode->validate();

				if($validMember && /*$validEducation && */$validMemberCode) {
 					$code 			= Util::generalMemberCode($membercode->status, $membercode->courses_id);
 					if (mb_strlen($code) == 6) {
 						// Create account
 						$account->username 			= $code;
 						$account->recover_password 	= Util::generalPass();
 						$account->password 			= Util::encrypting($account->recover_password);
 						$account->email				= $member->email;

 						if($account->save()) {
 							$userId	= $account->id;
 							// Create profile
 							$member->user_id	= $userId;
 							if ($member->save()) {
 								//Create code
 								$membercode->user_id 	= $userId;
 								$membercode->code 		= $code;
 								if ($membercode->save()) {
/* 									//Create education
 									$education->code_id = $code;
 									$education->save();*/
 									return true;
 								}
 							}
 						}
 					}
				}
				else {
					$tempError	= array();
					// Print error
					$err_msg .= "Dòng " . $row . "(" . $data['fullname'] . ")<br>";
					foreach ($member->errors as $key => $value) {
						$err_msg .= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;- " . $value[0] . "<br>";
					}
					foreach ($membercode->errors as $key => $value) {
						$err_msg .= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;- " . $value[0] . "<br>";
					}
				}
			}
		}
		else {
			return false;
		}
		if ($err_msg != "") {
			return $err_msg;
		}
    }

	/**
	 * Update_status
	 */
	public function actionUpdate_status($id, $returnUrl) {
		$model = $this->loadModel($id);
		$model->status = ($model->status == 1) ? 0 : 1;
		$model->update('status');

		if (!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array($returnUrl));
		exit;
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Member::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='member-form')
		{
			echo CActiveForm::validate($model);
			Util::app()->end();
		}
	}
}
